package com.lizemin.jdbc;

import lombok.Setter;

import javax.sql.DataSource;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author lzm
 * @date 2025/5/13 21:24
 * @description
 */
@Setter
public class PowerJdbcTemplate {

    private DataSource dataSource;

    /**
     * 查询多个对象, 目前不支持带参数的条件查询
     *
     * @param sql sql
     * @param clazz 要将结果封装成的对象类型
     * @return List<T> 返回查询结果的列表
     * @param <T> 泛型参数
     */
    public <T> List<T> queryForList(String sql, Class<T> clazz) {
        try (Connection connection = dataSource.getConnection();
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(sql)) {
            // 验证结果集不为空
            if (Objects.isNull(resultSet)) {
                return null;
            }
            ArrayList<T> result = new ArrayList<>();
            while (resultSet.next()) {
                // 处理查询结果，这里简单打印第一行数据的所有列
                ResultSetMetaData metaData = resultSet.getMetaData();
                int columnCount = metaData.getColumnCount();
                T t = clazz.newInstance();
                for (int i = 1; i <= columnCount; i++) {
                    Field filed = clazz.getDeclaredField(metaData.getColumnName(i));
                    filed.setAccessible(true);
                    Class<?> type = filed.getType();
                    if (type == Integer.class) {
                        String val = resultSet.getString(i);
                        filed.set(t, Integer.valueOf(val));
                        continue;
                    }
                    if (type == String.class) {
                        String val = resultSet.getString(i);
                        filed.set(t, val);
                    }
                }
                result.add(t);
            }
            return result;
        } catch (SQLException | InstantiationException | IllegalAccessException | NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }

}
